package com.suxin.spring.configuration;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.util.StringUtils;

/**
 * @author Tang
 * @classname ConfigurationPropertiesRegistry
 * @description [  ]
 * @date 2023/3/18 15:27
 */
public class ConfigurationPropertiesRegistry {

    private final BeanDefinitionRegistry registry;

    public ConfigurationPropertiesRegistry(BeanDefinitionRegistry registry) {
        this.registry = registry;
    }

    public void registry(Class<?> claz) {
        final MergedAnnotation<ConfigurationProperties> annotation =
                MergedAnnotations.from(claz, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY)
                .get(ConfigurationProperties.class);
        registry(claz, annotation);
    }

    private void registry(Class<?> claz, MergedAnnotation<ConfigurationProperties> annotation) {
        String name = getName(claz, annotation);
        this.registry.registerBeanDefinition(name,createBeanDefinition(claz));

    }

    private String getName(Class<?> claz, MergedAnnotation<ConfigurationProperties> annotation) {
        final String prefix = annotation.isPresent() ? annotation.getString("prefix") : "";
        return !StringUtils.isEmpty(prefix) ? prefix + "-" + claz.getName() : claz.getName();
    }

    /**
     * createBeanDefinition
     * @param claz claz
     * @return
     */
    public BeanDefinition createBeanDefinition(Class<?> claz) {
        final GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
        genericBeanDefinition.setBeanClass(claz);
        return genericBeanDefinition;
    }

}
